package com.guanyong.webapi.config;

import com.guanyong.webapi.controllers.api.qiniuDemo;
import com.guanyong.webapi.handle.GlobleData;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Administrator on 2017/9/20 0020.
 */
@Service
public class CreateVideoURLUtil {


    @Autowired
    GlobleData globleData;
    /**
     * 生成资源基于CDN时间戳防盗链的访问外链
     *
     * @param
     * @param
     * @throws MalformedURLException
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */

    public static String getAntiLeechAccessUrlBasedOnTimestamp(String url, String encryptKey, int durationInSeconds)
            throws MalformedURLException, UnsupportedEncodingException, NoSuchAlgorithmException {
        URL urlObj = new URL(url);
        String path = urlObj.getPath();

        long timestampNow = System.currentTimeMillis() / 1000 + durationInSeconds;
        String expireHex = Long.toHexString(timestampNow);

        String toSignStr = String.format("%s%s%s", encryptKey, path, expireHex);
        System.out.println("toSignStr:"+toSignStr);
        String signedStr = md5ToLower(toSignStr);
        System.out.println("signedStr:"+signedStr);
        String signedUrl = null;
        if (urlObj.getQuery() != null) {
            signedUrl = String.format("%s&sign=%s&t=%s", url, signedStr, expireHex);
        } else {
            signedUrl = String.format("%s?sign=%s&t=%s", url, signedStr, expireHex);
        }
        return signedUrl;
    }

    private static String md5ToLower(String src) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(src.getBytes("utf-8"));
        byte[] md5Bytes = digest.digest();
        return Hex.encodeHexString(md5Bytes);
    }


    public String getVideoURL(String videoName){
        String encryptKey = globleData.encryptKey;
        String fileKey = videoName;
        String encodedFileKey;
        try {
            // 考虑到文件名称会有中文，所以需要做urlencode
            encodedFileKey = URLEncoder.encode(fileKey, "utf-8");
            encodedFileKey=encodedFileKey.replaceAll("\\+", "%20");
            encodedFileKey=encodedFileKey.replaceAll("%2F", "/");
            String urlToSign = String.format("%s%s", globleData.CDN,encodedFileKey);
            // 有效期
            int duration = globleData.duration;

            String signedUrl = CreateVideoURLUtil.getAntiLeechAccessUrlBasedOnTimestamp(urlToSign, encryptKey, duration);
            return signedUrl;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "";
    }


    public static void main(String[] args) {
//        String encryptKey = globleData.encryptKey;
        String encryptKey = "4db9d1b92da96d9813990dab8e994b8b68a8998b";
        // 待加密链接
        String fileKey = "修道院惊魂 片花.mp4";
//        String fileKey = "DIR1/中文/vodfile.mp4";
//        String fileKey = "test.txt";
        String encodedFileKey;
        try {
            // 考虑到文件名称会有中文，所以需要做urlencode
            encodedFileKey = URLEncoder.encode(fileKey, "utf-8");
            encodedFileKey=encodedFileKey.replaceAll("\\+", "%20");
            encodedFileKey=encodedFileKey.replaceAll("%2F", "/");
//            encodedFileKey=encodedFileKey+"?v=1.2";
            String urlToSign = String.format("http://test.fdybee.com/%s", encodedFileKey);
//            String urlToSign = String.format("http://xxx.yyy.com/%s", encodedFileKey);
            // 有效期
            int duration = 100;

            String signedUrl = qiniuDemo.getAntiLeechAccessUrlBasedOnTimestamp(urlToSign, encryptKey, duration);
            System.out.println(signedUrl);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

}
